package com.quan.sport.gateway.failback;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import com.quan.common.base.bean.ResultBean;

@Component
public class GatewayFaillbackProvider implements FallbackProvider {

	private static final Logger logger = LoggerFactory.getLogger(FallbackProvider.class);

	private static final String AUTH_SERVICE_DISABLE = "微服务不可用";
	
	@Override
	public String getRoute() {
		// 指定要处理的 service。
		return "*";
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		cause.printStackTrace();
		if (cause instanceof HystrixTimeoutException) {
			return response(HttpStatus.OK, cause);
		} else {
			return response(HttpStatus.OK, cause);
		}
	}

	private ClientHttpResponse response(final HttpStatus status, Throwable cause) {
		return new ClientHttpResponse() {
			@Override
			public HttpStatus getStatusCode() throws IOException {
				return status;
			}

			@Override
			public int getRawStatusCode() throws IOException {
				return status.value();
			}

			@Override
			public String getStatusText() throws IOException {
				return status.getReasonPhrase();
			}

			@Override
			public void close() {
			}

			@Override
			public InputStream getBody() throws IOException {
				if (cause != null && cause.getMessage() != null) {
					logger.error("调用:{} 异常：{}", getRoute(), cause.getMessage());
					ResultBean errorException = ResultBean.errorMsg(cause.getMessage());
					return new ByteArrayInputStream(JSON.toJSONString(errorException).getBytes());
				} else {
					logger.error("调用服务:{} 异常：{}", getRoute(), AUTH_SERVICE_DISABLE);
					ResultBean errorException = ResultBean.errorMsg(AUTH_SERVICE_DISABLE);
					return new ByteArrayInputStream(JSON.toJSONString(errorException).getBytes());
				}
			}

			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_JSON);
				return headers;
			}
		};
	}
}
